import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../providers/product_provider.dart';
import '../../../utils/G.dart';
import '../../../providers/user_provider.dart';

void getProductSpecDialog(context) {
  var single = Provider.of<ProductProvider>(context, listen: false).single;
  var storeInfo =
      Provider.of<ProductProvider>(context, listen: false).storeInfo;

  showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
        topLeft: Radius.circular(20),
        topRight: Radius.circular(20),
      )),
      builder: (BuildContext context) {
        return StatefulBuilder(
            builder: (BuildContext ctx, StateSetter stateSetter) {
          return Stack(
            children: [
              Column(
                children: [
                  // 头部 - 展示商品图片和标题
                  _renderSpecHeader(context),

                  // 主体 - 展示商品规格
                  single ? Container() : _renderSpecBody(context, stateSetter),

                  // 尾部 - 商品的计数器
                  _renderSpecFooter(context, stateSetter)
                ],
              ),
              // 底部导航菜单
              Positioned(
                left: 0,
                bottom: 0,
                child: Row(
                  children: [
                    InkWell(
                      onTap: () async {
                        if (Provider.of<UserProvider>(context, listen: false)
                            .isLogin) {
                          var cartNum = Provider.of<ProductProvider>(context,
                                  listen: false)
                              .skuNum;
                          var res;
                          // 点击后，执行加入购物车
                          if (single) {
                            // 单规格商品
                            // storeInfo
                            res = await G.api.cart
                                .addToCart(storeInfo['id'], cartNum);
                          } else {
                            // 多规格商品
                            var spec = Provider.of<ProductProvider>(context,
                                    listen: false)
                                .getProductSpec();
                            res = await G.api.cart.addToCart(
                                spec['product_id'], cartNum, spec['unique']);
                          }

                          if (res != false && res['status'] == 200) {
                            Future.delayed(const Duration(milliseconds: 500),
                                () {
                              G.router.navigateTo(context, '/cart');
                            });
                          } else {
                            G.error('添加购物车失败');
                          }
                        } else {
                          G.router.navigateTo(context, '/login');
                        }
                      },
                      child: Container(
                          width: G.width / 2,
                          height: 50,
                          color: Colors.green,
                          alignment: Alignment.center,
                          child: const Text(
                            '加入购物车',
                            style: TextStyle(color: Colors.white, fontSize: 22),
                          )),
                    ),
                    InkWell(
                      onTap: () async {
                        if (Provider.of<UserProvider>(context, listen: false)
                            .isLogin) {
                          var cartNum = Provider.of<ProductProvider>(context,
                                  listen: false)
                              .skuNum;
                          var res;
                          // 点击后，执行加入购物车
                          if (single) {
                            // 单规格商品
                            // storeInfo
                            res = await G.api.cart
                                .addToCart(storeInfo['id'], cartNum, '', 1);
                          } else {
                            // 多规格商品
                            var spec = Provider.of<ProductProvider>(context,
                                    listen: false)
                                .getProductSpec();
                            res = await G.api.cart.addToCart(
                                spec['product_id'], cartNum, spec['unique'], 1);
                          }

                          if (res != false && res['status'] == 200) {
                            Future.delayed(const Duration(milliseconds: 500),
                                () {
                              Map<String, dynamic> p = {
                                'cartId': res['data']['cartId'],
                                'isNew': 1
                              };
                              G.router.navigateTo(context,
                                  '/order_confirm' + G.parseQuery(params: p));
                            });
                          } else {
                            G.error('立即购买失败');
                          }
                        } else {
                          G.router.navigateTo(context, '/login');
                        }
                      },
                      child: Container(
                          width: G.width / 2,
                          height: 50,
                          color: Theme.of(context).primaryColor,
                          alignment: Alignment.center,
                          child: const Text(
                            '立即购买',
                            style: TextStyle(color: Colors.white, fontSize: 22),
                          )),
                    )
                  ],
                ),
              )
            ],
          );
        });
      });
}

Widget _renderSpecFooter(context, stateSetter) {
  int skuNum = Provider.of<ProductProvider>(context).skuNum;

  return Column(
    mainAxisAlignment: MainAxisAlignment.start,
    children: [
      ListTile(
          title: Flex(
        direction: Axis.horizontal,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          const Text('数量'),
          Row(
            children: [
              InkWell(
                  onTap: () {
                    Provider.of<ProductProvider>(context, listen: false)
                        .decrement();
                  },
                  child: Container(
                    width: 20,
                    height: 20,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: skuNum > 1 ? Colors.white : Colors.black12,
                        border:
                            Border.all(width: 1, color: Colors.grey.shade300)),
                    child: skuNum > 1 ? const Text('-') : const Text(' '),
                  )),
              Container(
                  width: 20,
                  height: 20,
                  alignment: Alignment.center,
                  color: Colors.white,
                  child: Text(skuNum.toString())),
              InkWell(
                  onTap: () {
                    Provider.of<ProductProvider>(context, listen: false)
                        .increment();
                  },
                  child: Container(
                    width: 20,
                    height: 20,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        border:
                            Border.all(width: 1, color: Colors.grey.shade300)),
                    child: const Text('+'),
                  ))
            ],
          )
        ],
      ))
    ],
  );
}

// 展示商品规格
Widget _renderSpecBody(context, stateSetter) {
  // 获取商品规格
  var productAttr = Provider.of<ProductProvider>(context).productAttr;

  return Column(
    mainAxisAlignment: MainAxisAlignment.start,
    children: productAttr.map((item) {
      return ListTile(
          title: Flex(
        direction: Axis.horizontal,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(item['attr_name'].toString()),
          Row(
            children: item['attr_value'].map<Widget>((attrValue) {
              return InkWell(
                  onTap: () {
                    // 点选商品规格

                    stateSetter(() {
                      Provider.of<ProductProvider>(context, listen: false)
                          .selectSpec(item['id'], attrValue['attr']);
                    });
                  },
                  child: Container(
                    padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
                    margin: const EdgeInsets.only(left: 10),
                    height: 40,
                    color: attrValue['attr'] == item['selected']
                        ? Colors.green.shade100
                        : Colors.grey.shade200,
                    alignment: Alignment.center,
                    child: Text(attrValue['attr'].toString()),
                  ));
            }).toList(),
          )
        ],
      ));
    }).toList(),
  );
}

Widget _renderSpecHeader(context) {
  var spec =
      Provider.of<ProductProvider>(context, listen: false).getProductSpec();
  var single = Provider.of<ProductProvider>(context, listen: false).single;
  var storeInfo =
      Provider.of<ProductProvider>(context, listen: false).storeInfo;

  return Container(
    margin: const EdgeInsets.fromLTRB(10, 30, 10, 5),
    child: Flex(direction: Axis.horizontal, children: [
      G.imageWidget(single ? storeInfo['image'] : spec['image'],
          width: 100, height: 100),
      Expanded(
          child: Container(
        height: 100,
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              child: Text(
                (single ? storeInfo['store_name'] : spec['sku']).toString(),
                style: const TextStyle(fontSize: 16),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Container(
              child: Text(
                "￥ " + (single ? storeInfo['price'] : spec['price']).toString(),
                style: const TextStyle(fontSize: 16, color: Colors.red),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Container(
              child: Text(
                "库存 " +
                    (single ? storeInfo['stock'] : spec['stock']).toString(),
                style: const TextStyle(fontSize: 14, color: Colors.grey),
                overflow: TextOverflow.ellipsis,
              ),
            )
          ],
        ),
      ))
    ]),
  );
}
